class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int target1 = 0, target2 = 0;
        boolean isDouble = true;
        int target = (m + n) / 2;
        if ((m + n) % 2 != 0) {
            isDouble = false;
            target++;
        }
        int position = 0;
        int pos1 = m / 2;
        int pos2 = n / 2;
        if (pos1 == 0) {
            return isDouble ? (nums2[pos2] + nums2[pos2 - 1]) / 2.0 : nums2[pos2];
        } else if (pos2 == 0) {
            return isDouble ? (nums1[pos1] + nums1[pos1 - 1]) / 2.0 : nums1[pos1];
        }
        if (nums1[pos1] > nums2[pos2]) {
            position = pos1 + pos2 + 1;
            if (position != target) {
                for (int i = pos2 + 1; i < n; i++) {
                    if (nums1[pos1] < nums2[i]) {
                        pos1++;
                    }
                    position++;
                    if (position == target) {
                        target1 = nums1[pos1];
                        target2 = nums2[i];
                        break;
                    }
                }
            } else if (position == target) {
                target1 = nums1[pos1];
                target2 = nums2[pos2];
            }
        } else {
            position = pos1 + pos2 + 1;
            if (position != target) {
                for (int i = pos1 + 1; i < n; i++) {
                    if (nums2[pos2] < nums1[i]) {
                        pos2++;
                    }
                    position++;
                    if (position == target) {
                        target1 = nums1[i];
                        target2 = nums2[pos2];
                        break;
                    }
                }
            } else if (position == target) {
                target1 = nums1[pos1];
                target2 = nums2[pos2];
            }
        }
        if (isDouble) {
            return (target1 + target2) / 2.0;
        } else {
            return (Math.min(target1, target2));
        }
    }
}

//runtime_error:Line 16: java.lang.ArrayIndexOutOfBoundsException: 0
//last_testcase:[2] []
